package com.bw.crop.controller;



import cn.hutool.core.util.IdUtil;
import cn.hutool.jwt.JWT;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;


import com.bw.aop.domain.ResultDTO;

import com.bw.aop.service.ResultService;
import com.bw.crop.config.LogObjectPool;
import com.bw.crop.config.PanObjectPool;
import com.bw.crop.config.ThreadPoolConfig;
import com.bw.crop.config.WaterMarkUtil;
import com.bw.crop.domain.*;
import com.bw.crop.service.*;
import com.bw.crop.units.Result;

import com.bw.itext.pdf.service.PdfService;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.itextpdf.kernel.pdf.PdfDocument;

import com.itextpdf.kernel.pdf.PdfPage;
import com.itextpdf.kernel.pdf.PdfReader;
import com.itextpdf.kernel.pdf.canvas.parser.PdfTextExtractor;
import com.itextpdf.kernel.pdf.canvas.parser.listener.LocationTextExtractionStrategy;



import com.ruoyi.common.core.domain.R;
import com.ruoyi.common.core.utils.poi.ExcelUtil;
import com.ruoyi.common.core.web.domain.AjaxResult;

import io.minio.MinioClient;
import io.minio.PutObjectArgs;
import io.minio.errors.*;
import io.swagger.models.auth.In;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.core.io.InputStreamResource;
import org.springframework.core.io.Resource;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.PostConstruct;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.time.LocalDateTime;
import java.time.temporal.ChronoUnit;
import java.util.*;
import java.util.concurrent.*;
import java.util.function.Function;
import java.util.stream.Collectors;

@RestController
@RequestMapping("/crop")
public class CropController {
    @Autowired
    SysCropsService cropsService;
    @Autowired
    MinioClient minioClient;
    @Autowired
    SysGrowService growService;
    @Autowired
    SysProducerService producerService;
    @Autowired
    SysHaulerService haulerService;
    @Autowired
    private ResultService resultService;
    @Autowired
    SysWayService sysWayService;
    @Autowired
    SysTypeService typeService;
    @Autowired
    private PdfService pdfService;

    // 获取单例对象池实例，假设初始大小为10
//    LogObjectPool logObjectPool = LogObjectPool.getInstance(10);
    //添加serri类行对象
//    PanObjectPool panObjectPool = new PanObjectPool(10); // 创建一个包含10个Serri对象的池

//    PanObjectPool panObjectPool =PanObjectPool.getInstance(10); // 创建一个包含10个Serri对象的池
    @Autowired
    private SysStashsService fsysStashsService;

    @Autowired
    private HttpServletRequest request;
    @Autowired
    private SysShengproductService sysShengproductService;

    @Autowired
    private SysProductProcessingService sysProductProcessingService;

    @Autowired
    private SysIngredientsCropService sysIngredientsCropService;

    @Autowired
    private SysStashareaService sysStashareaService;
    @Autowired
    private SysCropStashService sysCropStashService;
    @Autowired
    private SysLogsWarehouseService logsWarehouseService;
    @Autowired
    private SysLogsInventoryService logsInventoryService;
    @Autowired
    private HttpServletResponse response;
    @Autowired
    @Qualifier("threadPoolTaskExecutor")
    private  ThreadPoolTaskExecutor taskExecutor;
    @Autowired
    private DataSourceLoader dataSourceLoader;

    @RequestMapping("/list")
    public CompletableFuture<Result> list(Integer current, Integer size) {
        if(current==1){
            return CompletableFuture.supplyAsync(() -> {
                try {
                    // 异步加载数据
                    CompletableFuture<Result> futureA = dataSourceLoader.loadDataFromSourceA(size);
                    CompletableFuture<Result> futureB = dataSourceLoader.loadDataFromSourceB(size);
                    // 等待所有Future完成
                    CompletableFuture.allOf(futureA, futureB).join();
                    // 获取数据并合并
                    Result dataA = futureA.get(); // 获取数据源A的数据，如果还没完成会阻塞
                    Result dataB = futureB.get(); // 获取数据源B的数据，如果还没完成会阻塞
                    // 打印或处理数据...
                    System.out.println("Data from Source A: " + dataA.getData());
                    System.out.println("Data from Source B: " + dataB.getData());
                    List<Object> dataListA = (List<Object>) dataA.getData();
                    List<Object> dataListB = (List<Object>) dataB.getData();
                    List<Object> combinedDataList = new ArrayList<>(dataListA);
                    combinedDataList.addAll(dataListB);
                    // 创建新的PageInfo对象来包装合并后的数据列表（注意：这将丢失原始的分页信息）
                    PageInfo<?> combinedPageInfo = new PageInfo<>(combinedDataList);
                    return Result.success(combinedPageInfo);
                } catch (InterruptedException | ExecutionException e) {
                    e.printStackTrace();
                }
                return Result.fail("An error occurred while fetching data for home page");
            }, taskExecutor);
        }
        return CompletableFuture.supplyAsync(() -> {
            PageHelper.startPage(current, size);
            List<SysCrops> list = cropsService.list();
            PageInfo<SysCrops> pageInfo = new PageInfo<>(list);
            System.out.println("在异步线程中查询并准备分页结果");
            return Result.success(pageInfo);
        }, taskExecutor); // 使用您之前定义的taskExecutor
    }


    @RequestMapping("/total")
    public Result gettotal(Integer current,Integer size){
        PageHelper.startPage(current,size);
        List<SysCrops> list = cropsService.list();
        return Result.success(new PageInfo<>(list).getTotal());
    }


    /**
     * 农作物添加
     *
     * @param crops
     * @return
     */
    @RequestMapping("saveCrop")
    public CompletableFuture<AjaxResult> saveCrop(@RequestBody SysCrops crops) {
        Map<String, Object> getuser = getuser();
        CompletableFuture<AjaxResult> future = CompletableFuture.supplyAsync(() -> {
            // 假设这个方法返回用户信息
            crops.setUserName(getuser.get("name").toString());
            boolean save = cropsService.save(crops);
            return save?AjaxResult.success():AjaxResult.error();
        }, taskExecutor);
        return future;
    }


    /**
     * 添加照片
     */
    @RequestMapping("/addPic")
    public String addPic(MultipartFile file) throws IOException, ServerException, InvalidBucketNameException, InsufficientDataException, ErrorResponseException, NoSuchAlgorithmException, InvalidKeyException, InvalidResponseException, XmlParserException, InternalException {
        // 访问图片时,图片在minio中的路径
        String url = "http://10.39.35.39:9000/";
        //操作文件
        // 获取上传的文件的名称   meinv.png  --->  123121232131231.png
        String fileName = file.getOriginalFilename();
        // 动态生成唯一的图片名称
        String realName = new SimpleDateFormat("yyyy/MM/dd/").format(new Date())
                + IdUtil.getSnowflake().nextId()
                + fileName.substring(fileName.lastIndexOf("."));
        System.out.println("--------"+realName);
        // 构建上传的文件对象
        PutObjectArgs objectArgs = PutObjectArgs.builder()
                .object(realName) // 指定上传的文件名称
                .bucket("imgs")  // 指定上传文件的存储位置
                .contentType(file.getContentType()) // 指定上传的文件类型
                .stream(file.getInputStream(), file.getSize(), -1).build();
        // 将上传的文件保存到minio中
        minioClient.putObject(objectArgs);
        // 拼接文件的路径
        url+="imgs/"+realName;
        System.out.println("============"+url);
        return url;
    }
    /**
     * 添加详情
     * @return
     */
    @RequestMapping("/saveDetails")
    public AjaxResult saveDetails(@RequestBody SysGrow grow){
        //解析token，获取登录用户
        String token = request.getHeader("token");
        JWT of = JWT.of(token);
        Integer id = (Integer) of.getPayload("id");

        boolean save = growService.save(grow);
        return save?AjaxResult.success():AjaxResult.error();
    }

    /***
     * 根据农产品id查询 农产品信息
     * @param cid
     * @return
     */
    @RequestMapping("/getCropByCid")
    public AjaxResult getCropByCid(Integer cid){
        SysCrops byId = cropsService.getById(cid);
        return AjaxResult.success(byId);
    }

    /**
     * 根据农产品id查询 生长情况
     * @param cid
     * @return
     */
    @RequestMapping("/getDetailsByCid")
    public AjaxResult getDetailsByCid(Integer cid){
        LambdaQueryWrapper<SysGrow> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(SysGrow::getCropId,cid);
        List<SysGrow> list = growService.list(wrapper);
        return AjaxResult.success(list);
    }
    /**
     * 通过cid修改农作物
     * @return
     */
    @RequestMapping("/uploadByCid")
    public AjaxResult uploadByCid(@RequestBody SysCrops crops){
        boolean save = cropsService.updateById(crops);
        return save?AjaxResult.success():AjaxResult.error();
    }

    /**
     * 查询生产商列表
     * @return
     */
    @RequestMapping("/getFactoryList")
    public AjaxResult producer(){
     return AjaxResult.success(sysShengproductService.list());
    }
    /**
     *查询运输员列表
     * @return
     */
    @RequestMapping("/getHaulerList")
    public AjaxResult hauler(){
        return AjaxResult.success(haulerService.list());
    }

    /**
     * 查询种植方式
     * @return
     */
    @RequestMapping("/wayList")
    public AjaxResult wayList(){
        return AjaxResult.success(sysWayService.list());
    }

    /**
     * 类型列表2
     * @return
     */
    @RequestMapping("typeList")
    public AjaxResult typeList(){
        return AjaxResult.success(typeService.list());
    }


    /**
     * 原料厂商列表
     * @return
     */
    @RequestMapping("/ingredientsList")
    public AjaxResult ingredientsList(){
        return AjaxResult.success(producerService.list());
    }

    /**
     * 通知物流后添加
     * @param ingredientsCrop
     * @return
     */
    @RequestMapping("saveIngredientsCropServiceList")
    public AjaxResult ingredientsCropServiceList(@RequestBody SysIngredientsCrop ingredientsCrop){
        boolean save = sysIngredientsCropService.save(ingredientsCrop);
        if (save){
            Integer cropId = ingredientsCrop.getCropId();
            SysCrops byId = cropsService.getById(cropId);
            byId.setPlantingCondition(1);
            cropsService.updateById(byId);
        }
        return save?AjaxResult.success():AjaxResult.error();
    }

    /**
     * 获取生产商的列表
     * @return
     */
    @RequestMapping("IngredientsCropServiceList")
    public R IngredientsCropServiceList(Integer current, Integer size){
        PageHelper.startPage(current,size);
        List<SysIngredientsCrop> list = sysIngredientsCropService.list();
        return R.ok(new PageInfo<>(list));
    }




    /**
     * 生产加工列表
     */
    @RequestMapping("/produpresslist")
    public Result produpresslist(Integer current,Integer size){
        PageHelper.startPage(current,size);
        List<SysProductProcessing> list = sysProductProcessingService.list();
        return Result.success(new PageInfo<>(list));
    }

    /**
     * 仓库管理列表
     */
    @RequestMapping("/stashcropList")
    public Result stashcropList(Integer current,Integer size){
        PageHelper.startPage(current,size);
        List<SysCropStash> list = sysCropStashService.getlist();
        System.out.println("ncknckd"+list);
        return Result.success(new PageInfo<>(list));
    }

    @RequestMapping("/nnn")
    public Result nnn(Integer current,Integer size){
        // 计算offset，注意MySQL的LIMIT是从0开始的，所以offset = (current - 1) * size
        int offset = (current - 1) * size;

        // 创建参数Map
        Map<String, Object> params = new HashMap<>();
        params.put("offset", offset);
        params.put("size", size);
        List<SysCropStash> list = sysCropStashService.getlist();
//        // 创建PageInfo对象并设置总记录数（通常你需要另一个查询来获取这个数）
//        PageInfo<SysCropStash> pageInfo = new PageInfo<>(list);
//        // 假设你有一个方法来获取总记录数
//        pageInfo.setTotal(pageInfo.getTotal());
        return Result.success(list);
    }

    /**
     * 质检完通知加工厂
     */
    @RequestMapping("/goproduct")
    public Result goproduct(@RequestBody SysIngredientsCrop byId){
        //获取登录用户
        Map getuser = getuser();
        System.out.println(getuser);

        byId.setUserName(getuser.get("name").toString());
        byId.setStatus(byId.getStatus());
        byId.setPic(byId.getPic());
        sysIngredientsCropService.updateById(byId);
        //没毒的到加工厂
        //原料厂的数据
//        SysIngredientsCrop byId = sysIngredientsCropService.getById(id);
        //添加一条待加工的数据
        SysProductProcessing sysProductProcessing = new SysProductProcessing();

        sysProductProcessing.setCropId(byId.getCropId());


        //查询原料厂商
        SysProducer ingredients = producerService.getById(byId.getIngredientsId());
        sysProductProcessing.setIngredientsName(ingredients.getProducerName());
        sysProductProcessing.setProcessingStatus("未加工");
        sysProductProcessing.setStashStatus("未入库");
        sysProductProcessing.setPpId(byId.getShengproductId());
        sysProductProcessing.setIngredientsId(byId.getId());
        sysProductProcessing.setStatus(byId.getStatus());




        //查询作物名称
        SysCrops crops = cropsService.getById(byId.getCropId());
        sysProductProcessing.setCropName(crops.getName());

        //添加一条代加工的数据
        sysProductProcessingService.save(sysProductProcessing);
        return Result.success();

    }



    /**
     * 去加工
     */
//    @PhoneValidator("管理员")
    @RequestMapping("/gopress")
    public R gopress(@RequestBody SysProductProcessing byId){
        //生产加工后的标准
        byId.setCropRule(byId.getStandard());
        byId.setSize(byId.getSize());
        byId.setNum(byId.getNum());
        byId.setProcessingStatus("已加工");
        byId.setStashStatus("待处理");
        sysProductProcessingService.updateById(byId);
        return R.ok();
    }


    /**
     * 去入库
     */
//    @PhoneValidator("普通人")
    @RequestMapping("/gostorage")
    public R gostorage(@RequestBody SysProductProcessing byId,Integer stashId,Integer fstashId){
        //入库
        SysCropStash sysCropStash = new SysCropStash();
        sysCropStash.setCropName(byId.getCropName());
        sysCropStash.setPpId(byId.getPpId());
        sysCropStash.setCropRule(byId.getCropRule());
        sysCropStash.setCropId(byId.getCropId());
        sysCropStash.setIngredientsName(byId.getIngredientsName());
        sysCropStash.setIngredientsId(byId.getIngredientsId());
        sysCropStash.setCreateDate(new Date());
        sysCropStash.setNum(byId.getNum());
        sysCropStash.setFsid(fstashId);

        //去ru库
        //存放的库区
        sysCropStash.setStashId(stashId);
        byId.setStashStatus("已入库");
        sysProductProcessingService.updateById(byId);
        //入库成功
        sysCropStashService.save(sysCropStash);

        SysLogsWarehouse logsWarehouse = new SysLogsWarehouse();
        logsWarehouse.setOutInWarehouse(0);
        logsWarehouse.setCreateDate(new Date());
        logsWarehouse.setFstashId(fstashId);
        logsWarehouse.setOutInGoods(byId.getCropName());
        logsWarehouse.setOutInSum(byId.getNum());
//        logsWarehouse.setTransportId();
        //查询加工厂
        SysShengproduct shengproduct = sysShengproductService.getById(byId.getPpId());
        logsWarehouse.setInFromTo(shengproduct.getName());
        //获取登录人
        Map getuser = getuser();
        logsWarehouse.setOutInUser(getuser.get("name").toString());
        logsWarehouse.setStashId(stashId);

        logsWarehouseService.save(logsWarehouse);

        return R.ok();
    }


    /**
     * 获取登录用户
     */
    private Map getuser() {
        String token = request.getHeader("token");
        JWT of = JWT.of(token);
        String name = (String) of.getPayload("name");
        Integer id = (Integer) of.getPayload("id");
        Map<String, String> map = new HashMap<>();
        map.put("id",id+"");
        map.put("name",name);
        return map;
    }
    /**
     * 去分库区
     */
    @RequestMapping("/getstash")
    public R getstash(@RequestBody SysProductProcessing byId,Integer stashfId){
        LambdaQueryWrapper<SysStasharea> sysStashLambdaQueryWrapper = new LambdaQueryWrapper<>();
        if(byId.getStatus().equals("2")){
            sysStashLambdaQueryWrapper.eq(SysStasharea::getStatus,"有毒")
                    .eq(SysStasharea::getFid,stashfId)
                    .gt(SysStasharea::getStandard,byId.getCropRule())
                    .gt(SysStasharea::getSize,byId.getSize());
            List<SysStasharea> list = sysStashareaService.list(sysStashLambdaQueryWrapper);
            return R.ok(list);
        }
        sysStashLambdaQueryWrapper.eq(SysStasharea::getStatus,"无毒")
                .eq(SysStasharea::getFid,stashfId)
                .gt(SysStasharea::getStandard,byId.getCropRule())
                .gt(SysStasharea::getSize,byId.getSize());
        List<SysStasharea> list = sysStashareaService.list(sysStashLambdaQueryWrapper);
        return R.ok(list);
    }

    /**
     * 所有库区
     */
    @RequestMapping("/getstashList")
    public R getstashList(){
        List<SysStasharea> list = sysStashareaService.list();
        return R.ok(list);
    };

    /**
     * 仓库盘点
     */
    @RequestMapping("/takestock")
    public R takestock(Integer stashId,String cropName){
        //查询仓库数据
        LambdaQueryWrapper<SysCropStash> sysCropStashLambdaQueryWrapper = new LambdaQueryWrapper<>();
        sysCropStashLambdaQueryWrapper.eq(SysCropStash::getStashId,stashId);
        List<SysCropStash> cropStashList = sysCropStashService.getlist();
//        查询出来具体哪些农作物的数据
        List<SysCropStash> filtercroplist = cropStashList.stream()
                .filter(concent -> cropName.equals(concent.getCropName()))
                .collect(Collectors.toList());
//        计算所有这种农作物的数量和
        int cropSum = filtercroplist.stream()
                .mapToInt(SysCropStash::getNum)
                .sum();

        //从记录表中获取该农作物的出入情况
        return R.ok();
    }

    /**
     * 所有仓库
     * @return
     */
    @RequestMapping("/getfstashList")
    public R getfstashList(){
        List<SysStashs> list = fsysStashsService.list();
        return R.ok(list);
    }
    /**
     * 根据所选库展示库区
     */
    @RequestMapping("/changestashId")
    public R changestashId(Integer id){
        LambdaQueryWrapper<SysStasharea> sysStashareaLambdaQueryWrapper = new LambdaQueryWrapper<>();
        sysStashareaLambdaQueryWrapper.eq(SysStasharea::getFid,id);
        List<SysStasharea> list = sysStashareaService.list(sysStashareaLambdaQueryWrapper);
        return R.ok(list);
    }

    /**
     * 根据所选库区展示商品
     * @throws Exception
     */
    /**
     * 根据所选库区展示作物
     */
    @RequestMapping("/changecropId")
    public R changecropId(Integer stashId, Integer fstashId) {
        LambdaQueryWrapper<SysCropStash> sysCropStashLambdaQueryWrapper = new LambdaQueryWrapper<>();
        sysCropStashLambdaQueryWrapper.eq(SysCropStash::getStashId, stashId)
                .eq(SysCropStash::getFsid, fstashId);
        List<SysCropStash> list = sysCropStashService.list(sysCropStashLambdaQueryWrapper);
        // 使用Stream API来根据name去重
        List<SysCropStash> distinctListByName = list.stream()
                .collect(Collectors.toMap(
                        SysCropStash::getCropName, // keyMapper - 从SysCropStash中提取name作为Map的键
                        Function.identity(),    // valueMapper - 直接使用SysCropStash对象作为Map的值
                        (existing, replacement) -> existing, // mergeFunction - 如果有冲突，保留现有的对象
                        LinkedHashMap::new        // mapFactory - 使用LinkedHashMap来保留插入顺序
                ))
                .values()                    // 获取Map的values集合，即为去重后的List
                .stream()                    // 将Collection转换回Stream
                .collect(Collectors.toList());
        return R.ok(distinctListByName);
    }
    @RequestMapping("/pdf")
    public void pdf() throws Exception {
        List<SysCropStash> list = sysCropStashService.getCropList();
        //生成pdf文件
        pdfService.export(list,"1"+".pdf","盘点清单", SysCropStash.class);
    }

    /**
     * 加入盘点列表
     */
    @RequestMapping("/addpan")
    public R addpan(@RequestBody AddPanRequest addPanRequest) {
        Integer stashfId = addPanRequest.getStashfId();
        Integer stashId = addPanRequest.getStashId();
        Integer cropId = addPanRequest.getCropId();
        LambdaQueryWrapper<SysCropStash> sysCropStashLambdaQueryWrapper = new LambdaQueryWrapper<>();
        sysCropStashLambdaQueryWrapper.eq(SysCropStash::getFsid, stashfId);
        if (cropId != null) {
            sysCropStashLambdaQueryWrapper.eq(SysCropStash::getCropId, cropId);
        }
        if (stashId != null) {
            sysCropStashLambdaQueryWrapper.eq(SysCropStash::getStashId, stashId);
        }
        List<SysCropStash> list = sysCropStashService.list(sysCropStashLambdaQueryWrapper);

        List<SysLogsInventory> logsInventoryList = new ArrayList<>();
        for (SysCropStash sysCropStash : list) {
            SysLogsInventory logsInventory = new SysLogsInventory();
            logsInventory.setCropDataSum(sysCropStash.getNum());
            logsInventory.setCropName(sysCropStash.getCropName());
            Map getuser = getuser();
            logsInventory.setInventoryUser(getuser.get("name").toString());
            logsInventory.setWarehouseName(sysCropStash.getFsid()+"");
            logsInventory.setCropId(sysCropStash.getCropId());
            logsInventoryList.add(logsInventory);
        }
        logsInventoryService.saveBatch(logsInventoryList);
        return R.ok();
    }

    public static class AddPanRequest {
        private Integer stashfId;
        private Integer stashId;
        private Integer cropId; // 由于是对象属性，如果不传递则默认为 null

        // 标准的 getter 和 setter 方法
        public Integer getStashfId() {
            return stashfId;
        }

        public void setStashfId(Integer stashfId) {
            this.stashfId = stashfId;
        }

        public Integer getStashId() {
            return stashId;
        }

        public void setStashId(Integer stashId) {
            this.stashId = stashId;
        }

        public Integer getCropId() {
            return cropId;
        }

        public void setCropId(Integer cropId) {
            this.cropId = cropId;
        }
    }

    /**
     * 临时盘点列表
     */
    @RequestMapping("/panlist")
    public R panlist(Integer current, Integer size) {
        PageHelper.startPage(current, size);
        LambdaQueryWrapper<SysLogsInventory> sysLogsInventoryLambdaQueryWrapper = new LambdaQueryWrapper<>();
        sysLogsInventoryLambdaQueryWrapper.eq(SysLogsInventory::getYesNoStatus,"0");
        List<SysLogsInventory> list = logsInventoryService.list(sysLogsInventoryLambdaQueryWrapper);
        return R.ok(new PageInfo<>(list));
    }

    /**
     * 去盘点
     */
    @RequestMapping("/gopan")
    public R gopan(@RequestBody SysLogsInventory logsInventory) {
        LambdaQueryWrapper<SysCropStash> sysCropStashLambdaQueryWrapper = new LambdaQueryWrapper<>();
        sysCropStashLambdaQueryWrapper.eq(SysCropStash::getCropId, logsInventory.getCropId());
        SysCropStash one = sysCropStashService.getOne(sysCropStashLambdaQueryWrapper);

        logsInventory.setCropDataSum(one.getNum());
        logsInventory.setStatus(1);
        logsInventory.setCreateDate(new Date());
        Map getuser = getuser();
        logsInventory.setInventoryUser(getuser.get("name").toString());
        if (logsInventory.getCropRealitySum() == one.getNum()) {
            logsInventory.setTitle("仓库数量没问题！！！");
            logsInventoryService.updateById(logsInventory);
            return R.ok();
        }
        logsInventory.setTitle("仓库数量有差异！！！");
        logsInventoryService.updateById(logsInventory);
        return R.ok();
    }

    /**
     * 打印盘点单
     */
    @RequestMapping("/dayin")
    public void dayin(Integer id) {
        SysLogsInventory byId = logsInventoryService.getById(id);
        ExcelUtil<SysLogsInventory> sysLogsInventoryExcelUtil = new ExcelUtil<SysLogsInventory>(SysLogsInventory.class);
        sysLogsInventoryExcelUtil.exportExcel(response, Arrays.asList(byId), "盘点单");
    }

    public static List<String> kqids = new ArrayList<>();
    public static List<LocalDateTime> dateTimes = new ArrayList<>();
    private final ScheduledExecutorService scheduler = Executors.newScheduledThreadPool(1);


    private final   List<PdfList> pdfLists = new ArrayList<>();
    private final   String substring = UUID.randomUUID().toString().substring(0, 8);

    /**
     * 循环盘点
     */
    @RequestMapping("/xunpan")
    public void xunpan() throws IOException {
        LocalDateTime now = LocalDateTime.now();
        //查询多有库区
        List<SysStasharea> list = sysStashareaService.list();

        List<String> ckids = list.stream().map(sysStasharea -> sysStasharea.getId() + "-" + sysStasharea.getFid())
                .collect(Collectors.toList());
        System.out.println("sdvfvf" + ckids);
        for (int i = 0; i < ckids.size(); i++) {
            kqids.add(ckids.get(i));
            LocalDateTime nextTime = now.plusMinutes(i * 5);
            //转换日期
            System.out.println("q1111时间 " + (i + 1) + ": " + nextTime);
            dateTimes.add(nextTime);
        }
    }


    /**
     * 初始化啟動隨機生成時間段
     * @throws Exception
     */
    @PostConstruct
    public void initpl() throws Exception {
        xunpan();
        // 遍历仓库和盘点时间，并安排任务
        for (int i = 0; i < kqids.size(); i++) {
            final  LocalDateTime dateTime = dateTimes.get(i);
            final String s = kqids.get(i);
            String[] split = s.split("-");
            Integer s1 = Integer.valueOf(split[0]);
            Integer s2 = Integer.valueOf(split[0]);

            // 计算延迟时间
            long delayMillis = ChronoUnit.MILLIS.between(LocalDateTime.now(), dateTime);
            // 安排任务在延迟后执行
            scheduler.schedule(() -> {
                try {
                    sendReminderMessage(s1,s2);
                } catch (IOException e) {
                    throw new RuntimeException(e);
                }
            }, delayMillis, TimeUnit.MILLISECONDS);
        }

    }

    public void sendReminderMessage(Integer s1,Integer s2) throws IOException {
        xunRegular("2");
        List<SysCropStash> getlistxun = sysCropStashService.getlistxun(s1, s2);
        for (SysCropStash sysCropStash : getlistxun) {
            SysLogsInventory logsInventory = new SysLogsInventory();
            logsInventory.setCropId(sysCropStash.getCropId());
            logsInventory.setStatus(0);
            logsInventory.setCropName(sysCropStash.getCropName());
            logsInventory.setCropDataSum(sysCropStash.getNum());
            logsInventory.setWarehouseName(sysCropStash.getStashId()+"");
            logsInventory.setYesNoStatus("2");
            logsInventoryService.save(logsInventory);
        }
        System.out.println("---------"+"ssssssssssssss" + getlistxun);

        System.out.println("--------------发送成功");


    }
    @RequestMapping("/pdf/content")
    public  R getPdfContent() throws IOException, ParseException {
        List<String> lines = new ArrayList<>();
        List<SysLogsInventory> pdfcontents = new ArrayList<>();
        Path path = Paths.get("D:/pdf/sign/3.pdf");
        if(!Files.exists(path)){
            return R.fail("为到定期盘点的时间");
        }
        String filePath = "D:/pdf/sign/3.pdf";
        PdfReader pdfReader = new PdfReader(filePath);
        try (PdfDocument pdfDoc = new PdfDocument(pdfReader)) {
            for (int pageNum = 1; pageNum <= pdfDoc.getNumberOfPages(); pageNum++) {
                PdfPage page = pdfDoc.getPage(pageNum);
                String pageText = PdfTextExtractor.getTextFromPage(page, new LocationTextExtractionStrategy());
                // 使用 String 的 split 方法按行分割文本，并跳过第一行
                String[] textLines = pageText.split("\\r?\\n");
                if (textLines.length > 1) { // 确保至少有两行，以避免数组越界
                    for (int i = 2; i < textLines.length; i++) { // 跳过第一行（索引为 0）
                        lines.add(textLines[i]);
                    }
                }
            }
        }
        for (String line : lines) {
            String[] parts = line.split(" ");
            if (parts.length == 5) {
                String cropName=parts[0].trim();
                Integer cropId = Integer.valueOf(parts[1].trim());
                Integer cropRealitySum = Integer.valueOf(parts[2].trim());
                SysLogsInventory logsInventory = new SysLogsInventory();
                logsInventory.setCropDataSum(cropRealitySum);
                logsInventory.setStatus(0);
                logsInventory.setCropId(cropId);
                logsInventory.setCropName(cropName);
                logsInventory.setYesNoStatus("1");
                logsInventoryService.save(logsInventory);
                pdfcontents.add(logsInventory);
            }
        }

        return R.ok();
    }
    @RequestMapping("/dingpanlist")
    public R dingpanlist(Integer current,Integer size){
        PageHelper.startPage(current,size);
        LambdaQueryWrapper<SysLogsInventory> sysLogsInventoryLambdaQueryWrapper = new LambdaQueryWrapper<>();
        sysLogsInventoryLambdaQueryWrapper.eq(SysLogsInventory::getYesNoStatus,"1");
        List<SysLogsInventory> list = logsInventoryService.list(sysLogsInventoryLambdaQueryWrapper);
        return R.ok(new PageInfo<>(list));
    }
    /**
     * 定时任务：定期盘点超时发消息
     */
    @Scheduled(cron = "0 25 11 * * *")
    @RequestMapping("/dingdaqi")
    public void alRegular(){
        LambdaQueryWrapper<SysLogsInventory> sysLogsInventoryLambdaQueryWrapper = new LambdaQueryWrapper<>();
        sysLogsInventoryLambdaQueryWrapper.eq(SysLogsInventory::getYesNoStatus,"1")
                .eq(SysLogsInventory::getStatus,0);
        List<SysLogsInventory> list = logsInventoryService.list(sysLogsInventoryLambdaQueryWrapper);
        if(list!=null&&!list.isEmpty()){
            //发邮件提醒
            System.out.println("------------及时清单数据");
            xunRegular("1");
        }
    }
    /**
     * 循环盘点list
     */
    @RequestMapping("/xunpanlist")
    public R xunpanlist(Integer current,Integer size){
        PageHelper.startPage(current,size);
        LambdaQueryWrapper<SysLogsInventory> sysLogsInventoryLambdaQueryWrapper = new LambdaQueryWrapper<>();
        sysLogsInventoryLambdaQueryWrapper.eq(SysLogsInventory::getYesNoStatus,"2");
        List<SysLogsInventory> list = logsInventoryService.list(sysLogsInventoryLambdaQueryWrapper);
        return R.ok(new PageInfo<>(list));
    }

    /**
     * 定时任务：盘点时间到期提醒
     */
   public void xunRegular(String status){
        LambdaQueryWrapper<SysLogsInventory> sysLogsInventoryLambdaQueryWrapper = new LambdaQueryWrapper<>();
        sysLogsInventoryLambdaQueryWrapper.eq(SysLogsInventory::getYesNoStatus,status)
                .eq(SysLogsInventory::getStatus,0);
        List<SysLogsInventory> list = logsInventoryService.list(sysLogsInventoryLambdaQueryWrapper);
        if(list!=null&&!list.isEmpty()){
            //发邮件提醒
            System.out.println("------------及时清单数据");
            // 假设我们有一个服务来存储或更新结果
            String msg="及时盘点清单数据";
            ResultDTO resultDTO = new ResultDTO(true, msg);
            if(status.equals("2")){
                resultService.xaddResultDTO(resultDTO);
                return;
            }
            resultService.addResultDTO(resultDTO);
            return;
        }
       ResultDTO resultDTO = new ResultDTO();
       resultService.xaddResultDTO(resultDTO);
    }
    @RequestMapping("/latest")
    public R getLatestResult() {
        ResultDTO resultDTO = resultService.getLatestResult();
        return R.ok(resultDTO);
    }
    @RequestMapping("/xlatest")
    public R xgetLatestResult() {
        ResultDTO resultDTO = resultService.xgetLatestResult();
        return R.ok(resultDTO);
    }

    @RequestMapping("/null")
    public R hetnul(){
        ResultDTO resultDTO1 = new ResultDTO();
        resultService.daddResultDTO(resultDTO1);
        resultService.addResultDTO(resultDTO1);
        resultService.xaddResultDTO(resultDTO1);
        return R.ok();
    }
}
